package com.atguigu.boot.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletRequest;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.sql.PreparedStatement;
import java.util.Date;

//@ResponseBody   //代表这个类所有的请求都是写给浏览器的，而不是跳转到某个页面
//@Controller
@RestController
public class HelloController {

    public static Logger logger = LoggerFactory.getLogger(HelloController.class);


    @GetMapping("/hello/{id}")
    public ResponseEntity hello(@PathVariable("id") String id){
        System.out.println("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
        ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = sra.getRequest();
        logger.info("request.getRemoteHost(): "+request.getRemoteHost());
        logger.info("request.getRemoteAddr(): "+request.getRemoteAddr());
        logger.info("request.getProtocol(): "+request.getProtocol());
        logger.info("request.getPathInfo(): "+request.getPathInfo());
        logger.info("request.getRequestURI(): "+request.getRequestURI());
        logger.info("request.getRequestURL().toString(): "+request.getRequestURL().toString());
        logger.info("request.getQueryString(): "+request.getQueryString());
        logger.info("request.getServletPath(): "+request.getServletPath());

        HttpSession session = request.getSession();

        session.setAttribute("name", id);
        logger.info("session.getCreationTime(): "+String.valueOf(new Date(session.getCreationTime()).toString()));
        logger.info("session.getId: "+session.getId());
        logger.info("session.getLastAccessedTime(): "+new Date(session.getLastAccessedTime()).toString());
        logger.info("session.getServletContext().getContextPath(): "+session.getServletContext().getContextPath());
        logger.info("session.getServletContext().getServerInfo(): "+session.getServletContext().getServerInfo());

        Cookie[] cookies = request.getCookies();
        for(Cookie cookie : cookies){
            logger.info(cookie.getName()+" "+cookie.getValue());
        }
        return ResponseEntity.ok("hello "+id);
    }

    @GetMapping("/name")
    public ResponseEntity secondVisit(HttpServletRequest request){
        HttpSession session = request.getSession();
        Object name = session.getAttribute("name");
        return ResponseEntity.ok("acquire name from session: "+name);
    }
}
